//
//  AddressBookTool.m
//  AiShangJinFuSalesman
//
//  Created by AiShangTong on 2017/6/8.
//  Copyright © 2018年 AiShangTong. All rights reserved.
//

#import "AddressBookTool.h"

#import <AddressBook/AddressBook.h>

@implementation AddressBookTool

//获取通讯录；
+ (void)LoadPersonAddressBookBlock:(addressBookBlock)addressBookBlock {
    
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error){
            if (granted) {
                CFErrorRef *error1 = NULL;
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
                
                [AddressBookTool copyAddressBook:addressBook block:^(id obj) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        addressBookBlock(obj);
                    });
                }];
            }else {
                [HUD_Mao showCharacterMessage:@"需打开通讯录权限"];
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                    
                }
            }
        });
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        
        CFErrorRef *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        
        [AddressBookTool copyAddressBook:addressBook block:^(id obj) {
            dispatch_async(dispatch_get_main_queue(), ^{
                addressBookBlock(obj);
            });
        }];
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied) {
        [HUD_Mao showCharacterMessage:@"需打开通讯录权限"];
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
            
        }
    } else {
        [HUD_Mao showCharacterMessage:@"需打开通讯录权限"];
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
}

+ (void)copyAddressBook:(ABAddressBookRef)addressBook block:(addressBookBlock)addressBookBlock{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableDictionary *totalMutDic = [NSMutableDictionary dictionary];
        
        NSMutableArray *contactsMutArr = [NSMutableArray array]; //用子典类型 存放联系人数组
        
        CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
        CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
        
        //通讯录个数
        for ( int i = 0; i < numberOfPeople; i++){
            
            ABRecordRef person = CFArrayGetValueAtIndex(people, i);
            //读取电话多值
            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
            
            NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
            NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));

            NSString *name;
            if (firstName) {
                name = firstName;
                if (lastName) {
                    name = [lastName stringByAppendingString:firstName];
                }
            }else if (lastName) {
                name = lastName;
            }else {
                name = @"";
            }

            NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^'@#$%^&*()_+'\" - "];
            name = [[name componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
            name = [name stringByReplacingOccurrencesOfString:@"•" withString:@"·"];
            
            //一个联系人多个手机号
            for (int k = 0; k<ABMultiValueGetCount(phone); k++) {
                
                //获取該Label下的电话值
                NSString * personPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
                  if ([personPhone hasPrefix:@"+"]) {
                    personPhone = [personPhone substringFromIndex:3];
                }
                NSString *phoneNumber;
                NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\" - "];
                phoneNumber = [[personPhone componentsSeparatedByCharactersInSet:set]componentsJoinedByString:@""];
                
                NSMutableDictionary *peopleMutDic = [NSMutableDictionary dictionary];

                [peopleMutDic setObject:name forKey:@"name"];
                [peopleMutDic setObject:phoneNumber forKey:@"phone"];
                
                [contactsMutArr addObject:peopleMutDic];
            }
        }
        
        [totalMutDic setObject:contactsMutArr forKey:@"contacts"];
        addressBookBlock(totalMutDic);
    });
}


@end
